# -*- coding: utf-8 -*-

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtPrintSupport import *


class MainWindow(QMainWindow):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent=parent)
        self.setWindowTitle("打印图片示例")

        self.imageLabel = QLabel()
        self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.setCentralWidget(self.imageLabel)

        self.image = QImage()
        self.create_actions()
        self.create_menus()
        self.create_tool_bars()

        if self.image.load("./002.jpg"):
            self.imageLabel.setPixmap(QPixmap.fromImage(self.image))
            self.resize(self.image.width(), self.image.height())

    def create_actions(self):
        self.PrintAction = QAction(QIcon("./user_128px.png"), "打印", self)
        self.PrintAction.setShortcut("Ctrl+P")
        self.PrintAction.setStatusTip("打印")
        self.PrintAction.triggered.connect(self.slot_print)

    def create_menus(self):
        PrintMenu = self.menuBar().addMenu("打印")
        PrintMenu.addAction(self.PrintAction)

    def create_tool_bars(self):
        fileToolBar = self.addToolBar("Print")
        fileToolBar.addAction(self.PrintAction)

    def slot_print(self):
        printer = QPrinter()
        printDialog = QPrintDialog(printer, self)
        if printDialog.exec():
            painter = QPainter(printer)
            rect = painter.viewport()
            size = self.image.size()
            size.scale(rect.size(), Qt.KeepAspectRatio)
            painter.setViewport(rect.x(), rect.y(), size.width(), size.height())
            painter.setWindow(self.image.rect())
            painter.drawImage(0, 0, self.image)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec())